package com.epfresh.api.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.RequestEntity;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.AppActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.R;
import com.epfresh.api.universalimageloader.core.DisplayImageOptions;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wzh on 2016/5/9.
 */
public class PhotoUploadView extends RelativeLayout {

    private ImageView ivUpload;
    private View vTop;
    private View vUploadFail;
    private View vUploadProgress;


    private int ratioWidth = -1;
    private int ratioHeight = -1;

    private String photoId = "";
    private String url = "";
    private String filePath = "";
    private Object o1;

    private boolean isCircle;

    private boolean isUploading;

    public PhotoUploadView(Context context) {
        this(context, null, 0);
    }

    public PhotoUploadView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public PhotoUploadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PhotoUploadView);

        ratioHeight = ta.getInt(R.styleable.PhotoUploadView_ratio_height, 0);
        ratioWidth = ta.getInt(R.styleable.PhotoUploadView_ratio_width, 0);
        isCircle = ta.getBoolean(R.styleable.PhotoUploadView_is_circle, false);


        ta.recycle();
    }

    public View getvTop() {
        return vTop;
    }

    public void setvTop(View vTop) {
        this.vTop = vTop;
    }

    public void showTop() {
        vTop.setVisibility(VISIBLE);
    }

    public void hideTop() {
        vTop.setVisibility(GONE);
    }

    public void hideView() {
        ivUpload.setVisibility(GONE);
        setVisibility(INVISIBLE);
    }

    public void showView() {
        ivUpload.setVisibility(VISIBLE);
        setVisibility(VISIBLE);
    }

    public void showAddView() {
        ivUpload.setVisibility(GONE);
        setVisibility(VISIBLE);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        if (ratioHeight > 0 && ratioWidth > 0) {
            // 父容器传过来的宽度方向上的模式
            int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            // 父容器传过来的高度方向上的模式
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            // 父容器传过来的宽度的值
            int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft()
                    - getPaddingRight();
            // 父容器传过来的高度的值
            int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingBottom()
                    - getPaddingTop();

            height = (int) (width * ratioHeight / ratioWidth + 0.5f);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
                    MeasureSpec.EXACTLY);
        }


        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        vTop = findViewById(R.id.v_top);
        int index = -1;
        if (vTop != null) {
            for (int i = 0; i < getChildCount(); i++) {
                if (getChildAt(i) == vTop) {
                    index = i;
                    break;
                }
            }
        }


        if (vUploadProgress == null)
            vUploadProgress = View.inflate(getContext(), R.layout.layout_upload_progress, null);
        if (isCircle) {
            vUploadProgress.setBackgroundResource(R.drawable.uploading_cicle);
        }
        RelativeLayout.LayoutParams lp2 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        if (vUploadFail == null)
            vUploadFail = View.inflate(getContext(), R.layout.layout_upload_fail, null);

        if (isCircle) {
            vUploadFail.setBackgroundResource(R.drawable.upload_fail_cicle);
        }
        RelativeLayout.LayoutParams lp3 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        if (ivUpload == null) {
            if (isCircle) {
                ivUpload = new ShapedImageView(getContext(),ShapedImageView.SHAPE_MODE_ROUND_RECT, LocalDisplay.dp2px(20),LocalDisplay.dp2px(1),0xfcfcfc);
            } else {
                ivUpload = new ImageView(getContext());

            }
        }

        RelativeLayout.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        ivUpload.setScaleType(ImageView.ScaleType.CENTER_CROP);


        if (index > -1) {
            addView(vUploadProgress, index, lp2);
            addView(vUploadFail, index, lp3);
            addView(ivUpload, index, lp);
        } else {
            addView(ivUpload, lp);
            addView(vUploadFail, lp3);
            addView(vUploadProgress, lp2);
        }


        vUploadProgress.setVisibility(View.GONE);
        vUploadFail.setVisibility(View.GONE);

    }

    public void showProgress() {
        vUploadProgress.setVisibility(View.VISIBLE);
        vUploadFail.setVisibility(View.GONE);
    }
    public void hideProgress() {
        vUploadProgress.setVisibility(View.GONE);
        vUploadFail.setVisibility(View.GONE);
    }

    public void showImage() {
        vUploadProgress.setVisibility(View.GONE);
        vUploadFail.setVisibility(View.GONE);
        ivUpload.setVisibility(VISIBLE);
    }

    public void showFail() {
        vUploadProgress.setVisibility(View.GONE);
        vUploadFail.setVisibility(View.VISIBLE);
    }

    public boolean isFail() {
        return vUploadFail.getVisibility() == View.VISIBLE;
    }

    public ImageView getImagView() {
        return ivUpload;
    }

    DisplayImageOptions displayImageOptions;

    public DisplayImageOptions getImageOption() {
        if (displayImageOptions == null)
            displayImageOptions = new DisplayImageOptions.Builder()
                    .cacheInMemory(false)// 设置下载的图片是否缓存在内存中
                    .showImageOnLoading(R.drawable.def_img) // 设置图片在下载期间显示的图片
                    .showImageForEmptyUri(R.drawable.def_img)// 设置图片Uri为空或是错误的时候显示的图片
                    .showImageOnFail(R.drawable.def_img) // 设置图片加载/解码过程中错误时候显示的图片
                    .cacheOnDisk(false)// 设置下载的图片是否缓存在SD卡中
                    .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
                    // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//
                    // 设置图片以如何的编码方式显示
                    .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
                    // .decodingOptions(new Options())//设置图片的解码配置
                    // .delayBeforeLoading(int delayInMillis)//int
                    // delayInMillis为你设置的下载前的延迟时间
                    // 设置图片加入缓存前，对bitmap进行设置
                    // .preProcessor(BitmapProcessor preProcessor)
                    .resetViewBeforeLoading(false)// 设置图片在下载前是否重置，复位
                    .build();// 构建完成
        return displayImageOptions;
    }

    public void uploadImage(AppActivity context, String filePath, Object tag, OnRequestListener uploadListener) {
        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntity<Map<String, String>> data = new RequestEntity<>();
            data.setCmd(com.epfresh.api.constant.AppRouterConstant.cmd_store_merchant_file_upload);
            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);
            data.setParameters(map);
            context.request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadImage(AppActivity context, String filePath, Object tag) {
        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntity<Map<String, String>> data = new RequestEntity<>();
            data.setCmd(com.epfresh.api.constant.AppRouterConstant.cmd_store_merchant_file_upload);
            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);
            data.setParameters(map);
            context.request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadImage(AppActivity context, String filePath, Object tag, boolean isSecret) {
        uploadImage(context, filePath, tag, isSecret, uploadListener);
    }

    public void uploadImage(AppActivity context, String filePath, Object tag, boolean isSecret, OnRequestListener uploadListener) {
        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntity<Map<String, String>> data = new RequestEntity<>();
            if (isSecret) {
                data.setCmd(com.epfresh.api.constant.AppRouterConstant.cmd_account_file_upload);
            } else {
                data.setCmd(com.epfresh.api.constant.AppRouterConstant.cmd_store_merchant_file_upload);
            }
            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);
            data.setParameters(map);
            context.request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            photoId = "";
            showFail();
            isUploading = false;
            L.e("upload", "upload image fail");

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            photoId = "";
            showFail();
            isUploading = false;
            L.e("upload", "upload image server fail");
        }

        @Override
        public void onStart(Object tag) {
            showProgress();
            isUploading = true;
        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            isUploading = false;
            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            if (id == Integer.MIN_VALUE) {
                showFail();
                photoId = "";
                return;
            } else {
                photoId = id + "";
                showImage();

            }
        }
    };


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getPhotoId() {
        return photoId;
    }

    public void setPhotoId(String photoId) {
        this.photoId = photoId;
    }

    public boolean isUploadSuccess(){
        return photoId != null && !"".equals(photoId);
    }
    public boolean isUploading(){
        return isUploading;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}
